<template>
  <div class="quiz-container">
    <el-card v-if="!showResult">
      <template #header>
        <div class="quiz-header">
          <h2>{{ categoryName }} - 知识问答</h2>
          <div class="progress">
            <span>进度：{{ currentIndex + 1 }}/{{ questions.length }}</span>
            <el-progress
              :percentage="(currentIndex + 1) / questions.length * 100"
              :stroke-width="10"
              :show-text="false"
            />
          </div>
        </div>
      </template>
      
      <div v-loading="loading" class="quiz-content">
        <template v-if="currentQuestion">
          <div class="question-info">
            <el-tag :type="difficultyType" effect="light" class="difficulty-tag">
              难度：{{ difficultyText }}
            </el-tag>
            <h3 class="question-title">{{ currentQuestion.content }}</h3>
          </div>
          
          <div class="options-list">
            <el-radio-group v-model="userAnswers[currentIndex]" class="options-group">
              <el-radio
                v-for="(option, index) in currentQuestion.options"
                :key="index"
                :value="optionLabels[index]"
                class="option-item"
              >
                {{ option }}
              </el-radio>
            </el-radio-group>
          </div>
          
          <div class="quiz-footer">
            <el-button
              v-if="currentIndex > 0"
              @click="prevQuestion"
            >
              上一题
            </el-button>
            <el-button
              type="primary"
              :disabled="!userAnswers[currentIndex]"
              @click="nextQuestion"
            >
              {{ isLastQuestion ? '提交' : '下一题' }}
            </el-button>
          </div>
        </template>
      </div>
    </el-card>
    
    <el-card v-else class="result-card">
      <template #header>
        <div class="result-header">
          <h2>答题结果</h2>
        </div>
      </template>
      
      <div class="result-content">
        <el-result
          :icon="resultIcon"
          :title="resultTitle"
          :sub-title="resultSubTitle"
        >
          <template #extra>
            <el-button type="primary" @click="goBack">返回首页</el-button>
          </template>
        </el-result>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getQuestionList, submitAnswers } from '@/api/question'

const route = useRoute()
const router = useRouter()
const categoryId = route.params.categoryId

const loading = ref(false)
const questions = ref([])
const currentIndex = ref(0)
const userAnswers = ref([])
const showResult = ref(false)
const quizResult = ref(null)

const categoryMap = {
  1: '中药基础',
  2: '针灸推拿',
  3: '养生保健',
  4: '经典理论',
  5: '四季养生',
  6: '食疗方案'
}

const categoryName = computed(() => categoryMap[categoryId] || '未知分类')

const currentQuestion = computed(() => questions.value[currentIndex.value])

const isLastQuestion = computed(() => currentIndex.value === questions.value.length - 1)

const optionLabels = ['A', 'B', 'C', 'D']

const difficultyMap = {
  1: { type: 'info', text: '简单' },
  2: { type: 'success', text: '较易' },
  3: { type: 'warning', text: '中等' },
  4: { type: 'danger', text: '较难' },
  5: { type: '', text: '困难' }
}

const difficultyType = computed(() => {
  return difficultyMap[currentQuestion.value?.difficulty]?.type || 'info'
})

const difficultyText = computed(() => {
  return difficultyMap[currentQuestion.value?.difficulty]?.text || '未知'
})

const resultIcon = computed(() => {
  if (!quizResult.value) return 'error'
  const { totalScore } = quizResult.value
  return totalScore >= 80 ? 'success' : totalScore >= 60 ? 'warning' : 'error'
})

const resultTitle = computed(() => {
  if (!quizResult.value) return '提交失败'
  const { totalScore } = quizResult.value
  return `得分：${totalScore}分`
})

const resultSubTitle = computed(() => {
  if (!quizResult.value) return '请重试'
  const { correctCount, totalScore } = quizResult.value
  return `共答对 ${correctCount} 题，正确率 ${Math.round(totalScore)}%`
})

const fetchQuestions = async () => {
  loading.value = true
  try {
    const { data } = await getQuestionList(categoryId)
    questions.value = data
    userAnswers.value = new Array(data.length).fill('')
  } catch (error) {
    console.error('获取题目失败:', error)
  } finally {
    loading.value = false
  }
}

const prevQuestion = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--
  }
}

const nextQuestion = async () => {
  if (isLastQuestion.value) {
    await submitQuiz()
  } else {
    currentIndex.value++
  }
}

const submitQuiz = async () => {
  loading.value = true
  try {
    const { data } = await submitAnswers({
      categoryId: Number(categoryId),
      answers: questions.value.map((question, index) => ({
        id: question.id,
        userAnswer: userAnswers.value[index],
        difficulty: question.difficulty
      }))
    })
    quizResult.value = data
    showResult.value = true
  } catch (error) {
    console.error('提交答案失败:', error)
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.push('/')
}

onMounted(() => {
  fetchQuestions()
})
</script>

<style lang="scss" scoped>
.quiz-container {
  max-width: 800px;
  margin: 0 auto;
  
  .quiz-header {
    h2 {
      margin: 0 0 16px;
      font-size: 20px;
      color: #303133;
    }
    
    .progress {
      display: flex;
      align-items: center;
      gap: 12px;
      
      span {
        font-size: 14px;
        color: #606266;
        white-space: nowrap;
      }
      
      .el-progress {
        flex: 1;
      }
    }
  }
  
  .quiz-content {
    min-height: 400px;
    
    .question-info {
      margin-bottom: 24px;
      
      .difficulty-tag {
        margin-bottom: 12px;
      }
      
      .question-title {
        margin: 0;
        font-size: 18px;
        line-height: 1.6;
        color: #303133;
      }
    }
    
    .options-list {
      .options-group {
        display: flex;
        flex-direction: column;
        gap: 16px;
        
        .option-item {
          margin: 0;
          padding: 12px 16px;
          border-radius: 4px;
          background-color: #f5f7fa;
          transition: all 0.3s;
          
          &:hover {
            background-color: #ecf5ff;
          }
          
          &.is-checked {
            background-color: #ecf5ff;
            color: #409eff;
          }
        }
      }
    }
    
    .quiz-footer {
      margin-top: 24px;
      display: flex;
      justify-content: flex-end;
      gap: 12px;
    }
  }
  
  .result-card {
    .result-header {
      h2 {
        margin: 0;
        font-size: 20px;
        color: #303133;
        text-align: center;
      }
    }
    
    .result-content {
      padding: 24px 0;
    }
  }
}
</style> 